package com.lzx.iteam.net;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.DialerApp;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Megan on 15/12/10.
 */
public class GetGroupListMsg extends CcMsgStructure {

    private String TAG = "GetGroupListMsg";
    private Message mmCallback;
    private CloudDBOperation cloudDBOperation;
    private ArrayList<String> localIdList;
    private ArrayList<String> newIdList;
    private PreferenceUtil mPreferenceUtil;
    private String mUid;

    public GetGroupListMsg(Context mContext, Message callback) {
        mmCallback = callback;
        cloudDBOperation = new CloudDBOperation(mContext);
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");

    }

    public GetGroupListMsg(Context mContext) {
        cloudDBOperation = new CloudDBOperation(mContext);
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
    }


    @Override
    public void onReceive(JSONObject data) {
        long start = System.currentTimeMillis();
        try {
            ArrayList<CloudGroup> groupList = new ArrayList<CloudGroup>();
            newIdList = new ArrayList<String>();
            if(mmCallback == null){
                localIdList = (ArrayList<String>) mPreferenceUtil.getCloudContact("local_group_id");
                if (localIdList == null){
                    localIdList = new ArrayList<String>();
                }
                Log.d("GetGroupListMsg",localIdList.size() + "");
            }
            JSONArray groupData = data.getJSONArray(AsynHttpClient.KEY_CC_DATA);
            cloudDBOperation.deleteAllGroup();
            for (int i = 0; i < groupData.length(); i++) {
                JSONObject item = groupData.getJSONObject(i);
                CloudGroup groupitem = new CloudGroup();
                groupitem.groupId = item.getLong(AsynHttpClient.KEY_GROUP_ID);
                groupitem.groupName = item.getString(AsynHttpClient.KEY_GROUP_NAME);
                groupitem.contactId = item.getString(AsynHttpClient.KEY_CONTACT_ID);
                groupitem.groupType = item.getInt(AsynHttpClient.KEY_GROUP_TYPE);
                groupitem.userType = item.getString(AsynHttpClient.KEY_USER_TYPE);
                groupitem.contactCount = item.getInt(AsynHttpClient.KEY_CONTACT_COUNT);
                groupitem.memberCount = item.getInt(AsynHttpClient.KEY_MEMBER_COUNT);
                if (item.has(AsynHttpClient.KEY_UPDATE_TIME)){
                    groupitem.updateTime = DateUtil.jsonTime2Mills(item.getString(AsynHttpClient.KEY_UPDATE_TIME));
                }
                groupitem.groupImg = item.getString(AsynHttpClient.KEY_GROUP_IMG);

                // 红点暂时去掉了
//                groupitem.isNew = item.getString(AsynHttpClient.KEY_IS_NEW);
                groupitem.isNew = "1";
                groupitem.hasTags = item.getString(AsynHttpClient.KEY_HAS_TAGS);
                groupList.add(groupitem);
                cloudDBOperation.insertCloudGroup(groupitem,mUid);

                newIdList.add(groupitem.groupId+"");
                if (mmCallback == null && mPreferenceUtil != null){
                    for (String groupId : localIdList){
                        if (groupId.equals(groupitem.groupId+"")){
                            localIdList.remove(groupId);
                            break;
                        }
                    }
                }
                if (groupitem.hasTags.equals("1")) {

                    JSONArray jsonArray = item.getJSONArray(AsynHttpClient.KEY_TAGS);

                    if (jsonArray != null) {


                        JSONObject object = new JSONObject();
                        object.put("type", groupitem.userType);
                        object.putOpt("tags", jsonArray);


                        JSONObject jsonObject = new JSONObject();//data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                        jsonObject.putOpt(AsynHttpClient.KEY_CC_DATA, object);


                        SharedPreferences sp = DialerApp.mContext.getSharedPreferences("structure", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(groupitem.groupId + "", /*jsonArray*//*object*/jsonObject.toString());
                        //editor.commit();


                        //SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean(groupitem.groupId + "tag", true);
                        editor.commit();

                    }

                }


            }
            mPreferenceUtil.saveCloudContact("local_group_id",newIdList);
            if (mmCallback != null) {
                mmCallback.obj = groupList;
                mmCallback.sendToTarget();

                long over = System.currentTimeMillis();
                Log.d("GetGroupListMsg"," 耗时： "  + (over - start));
                return;
            }else{
                // 如果，某个号码簿已经被删除了，清楚数据库里这个号码簿的所有号码
                if (localIdList.size() > 0 && !mUid.equals("-1")) {
                    for (String id : localIdList) {
                        boolean flag = cloudDBOperation.deleteContactByGroupId(mUid, id);
                        Log.d("GetGroupListMsg", mUid + "  " + id + "  "+ flag);
                    }
                    Log.d("GetGroupListMsg", newIdList.size() + "");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long over = System.currentTimeMillis();
        Log.d("GetGroupListMsg"," 耗时：null  "  + (over - start));

        if (mmCallback != null) {
            mmCallback.arg1 = -1;
            mmCallback.sendToTarget();
        }
    }

    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }


}
